﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
using OLMS.DAL;
using OLMS.BLL;

namespace OLMS.Admin.Handlers
{
    /// <summary>
    /// OrdersManagerHandler 的摘要说明
    /// </summary>
    public class OrdersManagerHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string json = string.Empty;
            string[] orderStatusList = new string[]
           {
                "未付款","未发货","待收货","已收货","已退货"
           };
            string type = context.Request["t"];
            int status = 0;
            if (context.Request["s"] != null)
            {
                status = Convert.ToInt32(context.Request["s"]);
            }
            if(type!=null && type == "1")
            {
                //更改状态
                int orderId= Convert.ToInt32(context.Request["oid"]);
                OrderBLL.UpdateOrderStatus(orderId, status);
            }
            List<Orders> orderList = OrderBLL.GetAllOrdersList();
            var list = orderList.Where(o => o.OrderStatus == status).Select(o => new
            {
                OrderId = o.OrderId,
                UserName = o.Username,
                Phone = o.Phone,
                Address = o.Address,
                Email = o.Email,
                PostalCode = o.PostalCode,
                OrderDate = string.Format("{0:D}",o.OrderDate),
                Total = string.Format("{0:C}元",o.Total),
                OrderStatus = o.OrderStatus,
                OrderStatusName = orderStatusList[(int)o.OrderStatus]
            }).ToList();
            var data = new
            {
                UnPay= orderList.Where(o => o.OrderStatus ==0).Count(),
                UnDelivery = orderList.Where(o => o.OrderStatus == 1).Count(),
                UnGoods = orderList.Where(o => o.OrderStatus == 2).Count(),
                IsComplete = orderList.Where(o => o.OrderStatus == 3).Count(),
                IsReturn = orderList.Where(o => o.OrderStatus == 4).Count(),
                List=list
            };
            json = JsonConvert.SerializeObject(data);
            context.Response.ContentType = "application/json";
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}